package com.lwd.util;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.IOException;

public class HttpServiceUtils {
	
	private static final Logger logger = Logger.getLogger(HttpServiceUtils.class);
	
	/**
	 * get方式请求
	 * 
	 * @param httpClient             httpclient
	 * @param url                请求地址
	 * @param cookies            请求时附加 cookies
	 * @return
	 * @throws IOException
	 */
	public static String processGet(HttpClient httpClient, String url, Cookie[] cookies) throws IOException {
		if(httpClient == null || StringUtils.isEmpty(url))
			throw new IllegalArgumentException("http client and url cannot be null!!!");

		GetMethod getMethod = new GetMethod(url);
		try {
			return processGet(httpClient, getMethod, cookies);
		} finally {
			getMethod.releaseConnection();
		}
	}

	/**
	 * get方式请求
	 * @param httpClient httpClient
	 * @param getMethod 请求地址
	 * @param cookies 请求时附加cookies
	 * @return
	 * @throws IOException
	 */
	public static String processGet(HttpClient httpClient, GetMethod getMethod, Cookie[] cookies) throws IOException {
		if(httpClient == null || getMethod==null)
			throw new IllegalArgumentException("http client and get method cannot be null!!!");

		if(cookies != null) {
//			getMethod.setRequestHeader("Cookie", cookies[0].toString());
			httpClient.getState().addCookies(cookies);
		}

		int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
        	throw new HttpException("Method failed: "+ getMethod.getStatusLine());
        }

		return getMethod.getResponseBodyAsString();
	}

	/**
	 * get方式请求
	 *
	 * @param url 请求地址
	 * @return
	 * @throws IOException
	 */
	public static String processGet(String url) throws IOException {
		String data = processGet(new HttpClient(), url, null);
		return data;
	}

	/**
	 * post方式请求
	 *
	 * @param httpClient   httpclient
	 * @param url      请求地址地址
	 * @param params   post参数
	 * @param cookies  请求时附加cookies
	 * @return
	 * @throws IOException
	 */
	public static String processPost(HttpClient httpClient, String url, NameValuePair[] params, Cookie[] cookies) throws IOException {
		if (httpClient == null || StringUtils.isEmpty(url))
			throw new IllegalArgumentException("http client and url cannot be null!!!");
		PostMethod postMethod = new PostMethod(url);
		postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
		try {
			String data = processPost(httpClient, postMethod, params, cookies);
			return data;
		} finally {
			postMethod.releaseConnection();
		}
	}

	/**
	 * post 方式请求
	 *
	 * @param httpClient httpClient
	 * @param postMethod postMethod
	 * @param params 请求参数
	 * @param cookies 请求时附加cookies
	 * @return
	 * @throws IOException
	 */
	public static String processPost(HttpClient httpClient, PostMethod postMethod, NameValuePair[] params, Cookie[] cookies) throws IOException {
		if (httpClient == null || postMethod==null)
			throw new IllegalArgumentException("http client and post method cannot be null!!!");

		if (params!=null && params.length>0)
			postMethod.setRequestBody(params);
		if (cookies!=null && cookies.length>0) {
//            for (Cookie cookie : cookies)
////                response.addCookie(cookie);
//            }
            httpClient.getState().addCookies(cookies);
//			postMethod.setRequestHeader("Cookie", cookies);
//			httpClient.getState().addCookies(cookies);
		}
		int statusCode = httpClient.executeMethod(postMethod);
		if (statusCode != HttpStatus.SC_OK) {
            System.out.println(postMethod.getResponseBodyAsString());
			if(statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
				Header locationHeader = postMethod.getResponseHeader("Location");
				String redirectUrl = locationHeader.getValue();
				logger.info("request send redirect to "+redirectUrl);
				return processPost(httpClient, new PostMethod(redirectUrl), params, cookies);
			}
			throw new HttpException("Method failed: "+ postMethod.getStatusLine());
        }
		
		return postMethod.getResponseBodyAsString();
	}
}